package com.zx._12_算法.剑指offer._2022;

import com.zx._12_算法.TreeNode;

/**
 * https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof/
 */
public class 二叉树的最近公共祖先 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        // 没有找到数据，返回null
        if (root == null) {
            return null;
        }

        if (root.val == p.val || root.val == q.val) {
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        // 都不是null的时候，才是找到了
        if (left != null && right != null) {
            return root;
        }

        // 有一个值不是null
        if (left != null || right != null) {
            return left == null ? right : left;
        }

        return null;
    }
}
